接下來就來用迴圈做一些應用,就好比說建立圖形
for i in range(1,8):
print('*' * i)
結果:
*
**
***
****
*****
******
*******
又或者是九九乘法表
for i in range (1,4):
for j in range (1,4):
print((i),"*",j,"=",i*j)
結果:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
算階層的和
num = int(input("請輸入一個正整數: "))
factorialSum = 0
for i in range(num): # 階層的和
factorial = 1
for j in range(i+1): # 階層
factorial *= (j+1)
factorialSum += factorial
print(factorialSum)
結果:
請輸入一個正整數: 4
33
把輸入的數字顛倒
num = int(input("請輸入一段數字: "))
res = 0
while(num > 0):
res = res * 10 + num % 10
num //= 10
print(res)
結果:
請輸入一段數字: 1234
4321
輸入費氏數列的項數
count = int(input("請輸入項數: "))
if(count >= 1): print(str(0), end = ' ')
if(count >= 2): print(str(1), end = ' ')
num_1 = 0
num_2 = 1
for i in range(2, count):
print(str(num_1 + num_2), end = ' ')
tm = num_1
num_1 = num_2
num_2 = tm + num_2
結果:
請輸入項數: 3
0 1 1